﻿using System.Data;
using System.Windows.Forms;
using Util.Database;

namespace ConfigureNZBLoader.TreeItemTags
{
    class DownloadedEpisode : BaseTreeItemTag
    {
        private long ShowId;

        public DownloadedEpisode(long ID, long ShowId) : base(ID)
        {
            this.ShowId = ShowId;
        }

        public override EditControls.BaseEditControl EditControl
        {
            get
            {
                if (ID == 0)
                {
                    return null;
                }
                EditControls.DownloadedEpisode c = new EditControls.DownloadedEpisode();
                c.Open(ID);
                return c;
            }
        }

        public override TreeNode CreateNew(System.Windows.Forms.ContextMenuStrip menuNew, System.Windows.Forms.ContextMenuStrip menuDelete)
        {
            TreeNode t = new TreeNode("New");
            using (IDbCommand cmd = DB.CreateCommand())
            {
                cmd.CommandText = "insert into downloaded(id_show, season, episode, downloaddate, downloadaddress) values (?, 1, 1, datetime(), '')";
                IDataParameter par = cmd.CreateParameter();
                par.Value = ShowId;
                cmd.Parameters.Add(par);
                cmd.ExecuteNonQuery();

                cmd.Parameters.Clear();
                cmd.CommandText = "select max(id) from downloaded";
                t.Tag = new DownloadedEpisode((long)cmd.ExecuteScalar(), ShowId);
                t.ContextMenuStrip = menuDelete;
            }
            return t;
        }

        public override void Delete()
        {
            using (IDbCommand cmd = DB.CreateCommand())
            {
                cmd.CommandText = "delete from downloaded where id=?";
                IDataParameter par = cmd.CreateParameter();
                par.Value = ID;
                cmd.Parameters.Add(par);
                cmd.ExecuteNonQuery();
            }
        }
    }
}
